import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, Select, InputNumber, message, Tooltip, Modal, Form } from 'antd';
import React, { useState, useRef } from 'react';
import { history } from 'umi';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { queryVipBindCard, memberCardActivate } from './service';
import db from '@/utils/localstorage';
import { HasPermission } from '@/components/AuthComponent/HasPermission';
const AuthButton = HasPermission(Button);
const AuthDivider = HasPermission(Divider);

const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 7,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 15,
    },
    md: {
      span: 15,
    },
  },
};
const submitFormLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 10,
      offset: 7,
    },
  },
};
/**
 * 跳转编辑页
 * @param {*} record 
 */
const goToEdit = async record => {
  history.push(`/vip/bind-card/update/${record.id}`);
}

/**
 * 跳转新增页
 * @param {*} record 
 */
const goToSave = async => {
  history.push(`/vip/bind-card/save`);
}



const List = () => {
  const actionRef = useRef();
  const [form] = Form.useForm();
  const [visible, setVisible] = React.useState(false);
  const [bindingCardRecord, setBindingCardRecord] = React.useState({});
  const [dictTypeList, setDictTypeList] = useState(db.get("dictTypeList")['payment_method']);
  const columns = [
    {
      title: '会员卡名称',
      dataIndex: 'cardName',
    },
    {
      title: '绑定会员',
      dataIndex: 'name',
      render: (text, record) => <a onClick={() => go2VipDetail(record)}>{text}</a>
    },
    {
      title: '手机号',
      dataIndex: 'phone',
    },
    {
      title: '余额',
      dataIndex: 'balance',
      hideInSearch: true,
      render: (text, record) => record.cardType == '1' ? <span>{text}元</span> :
        record.cardType == '2' ? <Tooltip placement="top" title="永久有效">{text}次</Tooltip> :
          record.cardType == '3' ? <Tooltip placement="top" title={`到期时间${record.periodValidity}`}>{text}天</Tooltip> : ""
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        1: {
          text: '正常',
          status: 'Warning',
        },
        2: {
          text: '永久停卡',
          status: 'Error',
        },
        3: {
          text: '临时停卡',
          status: 'Error',
        },
        4: {
          text: '已失效',
          status: 'Error',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <AuthButton auth={[`vip:card:detail`]} type="link" onClick={() => go2Detail(record)}>详情</AuthButton>
          {
            record.status == '1' && <>
              <AuthDivider auth={['vip:card:detail', `vip:bind:card:renew`]} type="vertical"></AuthDivider>
              <AuthButton auth={[`vip:bind:card:renew`]} type="link" onClick={() => go2Renew(record)}>续卡</AuthButton>
            </>
          }
          {
            record.status == '1' && <>
              <AuthDivider auth={['vip:bind:card:renew', `vip:bind:card:deduction`]} type="vertical"></AuthDivider>
              <AuthButton auth={[`vip:bind:card:deduction`]} type="link" onClick={() => go2Deduction(record)}>扣卡</AuthButton>
            </>
          }
          {
            record.status == '1' && <>
              <AuthDivider auth={['vip:bind:card:deduction', `vip:bind:card:stop`]} type="vertical"></AuthDivider>
              <AuthButton auth={[`vip:bind:card:stop`]} type="link" onClick={() => go2Stop(record)}>停卡</AuthButton>
            </>
          }
          {
            (record.status == '2' || record.status == '3') && <>
              <AuthDivider auth={['vip:bind:card:deduction', `vip:bind:card:active`]} type="vertical"></AuthDivider>
              <AuthButton auth={[`vip:bind:card:active`]} type="link" onClick={() => go2Active(record)}>激活卡</AuthButton>
            </>
          }
        </>
      ),
    },
  ];

  /**
   * 会员详情
   * @param {*} record 
   */
  const go2VipDetail = (record) => {
    history.push(`/vip/center/detail/${record.memberId}`);
  }
  /**
   * 激活卡
   * @param {*} record 
   */
  const go2Active = (record) => {
    if (record.status == '2') {
      message.warn("永久停卡无法激活")
      return;
    }
    setVisible(true)
    setBindingCardRecord(record)
  }
  /**
   * 详情
   * @param {*} record 
   */
  const go2Detail = (record) => {
    history.push(`/vip/card/detail/${record.cardId}/${record.memberId}`);
  }

  /**
   * 续卡
   * @param {*} record 
   */
  const go2Renew = record => {
    history.push(`/vip/bind-card/renew/${record.cardId}/${record.memberId}`);
  }

  /**
   * 扣卡
   * @param {*} record 
   */
  const go2Deduction = record => {
    history.push(`/vip/bind-card/deduction/${record.cardId}/${record.memberId}`);
  }

  /**
   * 停卡
   * @param {*} record 
   */
  const go2Stop = record => {
    history.push(`/vip/bind-card/stop/${record.cardId}/${record.memberId}`);
  }
  /**
   * 确认激活
   */
  const handleAddOk = async () => {
    const fieldsValue = await form.validateFields();
    const hide = message.loading('正在激活');
    try {
      let result = await memberCardActivate({
        cardId: bindingCardRecord.cardId,
        memberId: bindingCardRecord.memberId,
        cardType: bindingCardRecord.cardType,
        ...fieldsValue
      });
      hide();
      if (result.code == 0) {
        message.success('激活成功，即将刷新');
        handleCancel();
        actionRef.current.reload()
        return true;
      } else {
        message.warn(result.message);
        return false;
      }
    } catch (error) {
      hide();
      message.error('激活失败，请重试');
      return false;
    }
  }

  /**
   * 取消激活
   */
  const handleCancel = () => {
    form.resetFields();
    setVisible(false)
    setBindingCardRecord({})
  }
  return (
    <PageHeaderWrapper>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={(action, { selectedRows }) => [
          <AuthButton auth={[`vip:bind:card:add`]} type="primary" icon={<PlusOutlined />} onClick={() => goToSave()}>新增</AuthButton>
        ]}
        tableAlertRender={({ selectedRowKeys, selectedRows }) => (
          <div>
            已选择{' '}
            <a
              style={{
                fontWeight: 600,
              }}
            >
              {selectedRowKeys.length}
            </a>{' '}
            项
          </div>
        )}
        request={params => {
          let _params = {
            pageNum: params.current,
            ...params,
          }
          delete _params.current
          return queryVipBindCard(_params)
        }}
        postData={result => result.list}
        columns={columns}
        rowSelection={{}}
      />
      {
        visible && <Modal
          title="激活卡"
          visible={visible}
          onOk={handleAddOk}
          onCancel={handleCancel}
        >
          <Form
            style={{
              marginTop: 8,
            }}
            form={form}
            name="basic"
          >
            <Form.Item
              {...formItemLayout}
              label="收费"
              name="money"
              rules={[{ required: true, message: '请输入收费金额' }]}
            >
              <InputNumber
                min={0}
                style={{ width: '100%' }}
                formatter={value => `${value}元`}
                parser={value => value.replace('元', '')}
              />
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label="支付方式"
              name="paymentMethod"
              rules={[{ required: true, message: '请选择支付方式' }]}
            >
              <Select style={{ width: '100%' }} placeholder="请选择">
                {
                  dictTypeList && dictTypeList.map((item, index) => <Select.Option key={index} value={item.value}>{item.label}</Select.Option>)
                }
              </Select>
            </Form.Item>
            <FormItem
              {...formItemLayout}
              label="销售人员"
              name="salesStaffId"
            >
              <Select style={{ width: '100%' }} placeholder="请选择">
                {
                  salesList && salesList.map((item, index) => <Select.Option value={item.userId} key={index}>{item.name}</Select.Option>)
                }
              </Select>
            </FormItem>
          </Form>
        </Modal>
      }
    </PageHeaderWrapper>
  );
};

export default List;
